package com.pzhu.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pzhu.mapper.*;
import com.pzhu.model.dto.BookableDto;
import com.pzhu.model.dto.LoginDto;
import com.pzhu.model.dto.StaffInfoDto;
import com.pzhu.model.entity.*;
import com.pzhu.model.help.ResponseResult;
import com.pzhu.model.vo.*;
import com.pzhu.service.StaffService;
import com.pzhu.utils.BeanCopyUtils;
import com.pzhu.utils.ToolUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【hs_staff(工作人员)】的数据库操作Service实现
 * @createDate 2023-12-16 22:51:28
 */
@Service
public class StaffServiceImpl extends ServiceImpl<StaffMapper, Staff>
        implements StaffService {

    @Autowired
    private StaffMapper staffMapper;
    @Autowired
    private CareerMapper careerMapper;
    @Autowired
    private StaffImageMapper staffImageMapper;
    @Autowired
    private BookableMapper bookableMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;


    @Override
    public ResponseResult login(LoginDto loginDto) {
        Staff staff = staffMapper.selectOne(
                new LambdaQueryWrapper<Staff>()
                        .eq(Staff::getJobNumber, loginDto.getJobNumber())
                        .or()
                        .eq(Staff::getPhone, loginDto.getJobNumber()));
        boolean matches = bCryptPasswordEncoder
                .matches(loginDto.getPassword(), staff.getPassword());

        StaffInfoVo staffInfoVo = BeanCopyUtils.copyBean(staff, StaffInfoVo.class);


        Career career = careerMapper.selectOne(new LambdaQueryWrapper<Career>()
                .eq(Career::getId, staff.getCareerId()));

        staffInfoVo.setCareer(career.getName());

        Map<String, Object> map = new HashMap<>();
        map.put("staff", staffInfoVo);


        return matches ? ResponseResult.ok(map) : ResponseResult.error("密码错误");
    }

    @Override
    public ResponseResult detail(Long id) {
        Staff staff = staffMapper.selectById(id);
        StaffDetailVo staffDetail = BeanCopyUtils.copyBean(staff, StaffDetailVo.class);
        staffDetail.setCareer(
                careerMapper.selectOne(
                        new LambdaQueryWrapper<Career>().eq(Career::getId, staffDetail.getCareerId())
                ).getName());

        staffDetail.setSwiperList(selectImg(id, "is_swiper"));
        staffDetail.setPresentationList(selectImg(id, "is_presentation"));
        staffDetail.setCertificateList(selectImg(id, "is_certificate"));

        Map<String, Object> map = new HashMap<>();
        map.put("staffDetail", staffDetail);
        return ResponseResult.ok(map);
    }

    @Override
    public ResponseResult saveInfo(StaffInfoDto staffInfoDto) {
        Staff staff = BeanCopyUtils.copyBean(staffInfoDto, Staff.class);
        staff.setCreateTime(new Date());
        staffMapper.updateById(staff);

        Long id = staffInfoDto.getId();

        //删除之前的照片
        staffImageMapper.delete(new LambdaQueryWrapper<StaffImage>().eq(StaffImage::getStaffId, id));

        //保存证书照片
        for (String url : staffInfoDto.getCertificates()) {
            StaffImage staffImage = new StaffImage();
            staffImage.setIsCertificate(true);
            staffImage.setUrl(url);
            staffImage.setStaffId(id);
            staffImage.setCreateTime(new Date());
            staffImageMapper.insert(staffImage);
        }
        //保存个人展示照片
        for (String url : staffInfoDto.getIntroduces()) {
            StaffImage staffImage = new StaffImage();
            staffImage.setIsSwiper(true);
            staffImage.setUrl(url);
            staffImage.setStaffId(id);
            staffImage.setCreateTime(new Date());
            staffImageMapper.insert(staffImage);
        }
        //保存轮播图照片
        for (String url : staffInfoDto.getSkills()) {
            StaffImage staffImage = new StaffImage();
            staffImage.setIsPresentation(true);
            staffImage.setUrl(url);
            staffImage.setStaffId(id);
            staffImage.setCreateTime(new Date());
            staffImageMapper.insert(staffImage);
        }
        return ResponseResult.ok();
    }

    @Override
    public ResponseResult bookTime(Long id, Integer area) {
        LambdaQueryWrapper<Bookable> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Bookable::getStaffId, id)
                .ge(Bookable::getStartTime, new Date());
        List<Bookable> bookableList = bookableMapper.selectList(queryWrapper);
        if (bookableList.size() == 0) {
            Map<String, Object> map = new HashMap<>();
            map.put("list", bookableList);
            return ResponseResult.ok(map);
        }

        List<BookableVoPlus> list = ToolUtils.handleBookableTime(bookableList, area);

        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        return ResponseResult.ok(map);
    }

    @Override
    public ResponseResult modifyTime(BookableDto bookableDto) {
        List<Bookable> bookableList = BeanCopyUtils.copyBeanList(bookableDto.getList(), Bookable.class);

        //删除该工作人员没有预约的时间记录
        LambdaQueryWrapper<Bookable> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Bookable::getStaffId, bookableDto.getStaffId())
                .eq(Bookable::getIsOrder, false);

        bookableMapper.delete(queryWrapper);

//        for (TimeDto timeDto : bookableDto.getList()) {
//            SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
//            timeDto.setStarT(new Date());
//            timeDto.setEndT(new Date());
//        }

//        System.err.println(bookableDto);
//        bookableMapper.batchInsert(bookableDto.getList());

        for (Bookable bookable : bookableList) {
            bookable.setCreateTime(new Date());
            bookableMapper.insert(bookable);
        }

        return ResponseResult.ok();
    }

    @Override
    public ResponseResult getByDate(String date, Integer area) {
        List<StaffDateVo> staffDateInfoVoList = staffMapper.getByDate(date);
        // 通过面积计算大概时间去匹配所有的可预约时间

        Long duration = Double.valueOf((area / 25.0) * 3600000).longValue();

        staffDateInfoVoList.forEach(v -> {
            List<Bookable> bookableList = bookableMapper
                    .selectList(new LambdaQueryWrapper<Bookable>()
                            .eq(Bookable::getStaffId, v.getId())
                            .ge(Bookable::getStartTime, new Date()));


            bookableList.forEach(t -> {
                System.err.println(t.getEndTime().getTime() - t.getStartTime().getTime());
                System.err.println(duration);
                System.err.println(t.getEndTime().getTime() - t.getStartTime().getTime() >= duration);
            });

            List<Bookable> collect = bookableList.stream().filter(bookable ->
                    bookable.getEndTime().getTime() - bookable.getStartTime().getTime() >= duration
            ).collect(Collectors.toList());

            v.setCount(collect.size());
        });

        Map<String, Object> map = new HashMap<>();
        map.put("list", staffDateInfoVoList.stream()
                .filter(v -> v.getCount() != 0)
                .collect(Collectors.toList()));

        return ResponseResult.ok(map);
    }

    @Override
    public ResponseResult orderTak(Long id, Long orderId) {
        //查询阿姨信息
        Staff staff = staffMapper.selectById(id);

        Order order = orderMapper.selectById(orderId);

        order.setStaffId(id);
        order.setStaffName(staff.getUsername());
        order.setStatus(2);
        orderMapper.updateById(order);

        return ResponseResult.ok();
    }

    @Override
    public ResponseResult myOrder(Long id, Integer status) {
        //首先对订单进行判断是否过期
        Order order = new Order();
        order.setStatus(3);
        orderMapper.update(order, new LambdaQueryWrapper<Order>()
                .and(x -> x.eq(Order::getStatus, 1)
                        .or()
                        .eq(Order::getStatus, 2))
                .lt(Order::getEndTime, new Date()));

        List<Order> orderList = orderMapper
                .selectList(new LambdaQueryWrapper<Order>()
                        .eq(Order::getStaffId, id)
                        .eq(status != -1, Order::getStatus, status)
                        .orderByDesc(Order::getStartTime)
                );
        Map<String, Object> map = new HashMap<>();
        map.put("list", orderList);
        return ResponseResult.ok(map);
    }

    @Override
    public ResponseResult compare() {
        List<Staff> staffInfoList = staffMapper.compare();
        List<StaffCompareVo> staffCompareVos = BeanCopyUtils.copyBeanList(staffInfoList, StaffCompareVo.class);
        return ResponseResult.ok().put("list",staffCompareVos);
    }

    private List<String> selectImg(Long id, String field) {

        QueryWrapper<StaffImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(field, true).eq("staff_id", id);
        List<StaffImage> items = staffImageMapper.selectList(queryWrapper);
        return items.stream().map(StaffImage::getUrl).collect(Collectors.toList());// 取出其中一列
    }
}




